package com.wusuowei.oauthclient.exception;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * @description 匿名用户访问无权限资源时的异常
 * @author LGY
 * @date 2023/04/06 23:26
 * @version 1.0.0
 */
@Component
public class MyAuthenticationEntryPoint implements AuthenticationEntryPoint {

    @Autowired
    private ObjectMapper objectMapper;


    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response,
                         AuthenticationException authException) throws ServletException {
        try {
            // 1. 检查看服务端是否已将数据输出到客户端，如果已返回，则不处理
            if (response.isCommitted()) {
                return;
            }
            // 2. 封装结果信息，应该使用统一结果集封装，这里使用Map
            response.setStatus(HttpStatus.UNAUTHORIZED.value());
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json;charset=utf-8");
            Map<String, Object> result = new HashMap<>();
            result.put("code", 401);
            result.put("msg", authException.getMessage());
            result.put("result", "认证失败");
            objectMapper.writeValue(response.getOutputStream(), result);
        } catch (Exception e) {
            throw new ServletException(e);
        }
    }
}
